class Drag {
  private clientX: number = 0
  private clientY: number = 0
  private body?: HTMLBodyElement

  public run(): void {
    document.addEventListener('DOMContentLoaded', () => {
      this.body = document.body as HTMLBodyElement
      this.body.addEventListener('mousedown', this.mouseDown.bind(this))
    })
  }

  private mouseDown(e: MouseEvent): void {
    this.clientX = e.clientX
    this.clientY = e.clientY

    const mouseMoveCallback = this.mouseEvent.bind(this)
    this.body?.addEventListener('mousemove', mouseMoveCallback)
    this.body?.addEventListener('mouseup', () => {
      this.body?.removeEventListener('mousemove', mouseMoveCallback)
    })

    // 事件传递需要时间,如果鼠标移动过快,那么添加此段代码会导致 mousemove 事件提前结束
    // this.body?.addEventListener('mouseout', () => {
    //   this.body?.removeEventListener('mousemove', mouseMoveCallback)
    // })
  }

  private mouseEvent(e: MouseEvent): void {
    const x = e.clientX - this.clientX
    const y = e.clientY - this.clientY
    console.log(x, y)
    // 更改窗口位置
    window.api.winDrag({ x, y })
  }
}

export default (): { drag: Drag } => {
  const drag = new Drag()
  return {
    drag
  }
}
